package com.maijinjie.admin.interceptor;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.maijinjie.common.action.dwz.bean.DwzStatusBean;
import com.maijinjie.common.session.SessionContext;
import com.maijinjie.common.util.JsonUtil;

/**
 * 授权拦截器，如果检测到没有授权则不能访问指定URL
 * @version 1.0
 * @author GhostarX ( 王欣逸 ) 100992995@qq.com &copy;广州迈今捷信息科技有限公司
 * @data 2013-8-14 下午7:33:26
 */
@Component("authInterceptor")
public class AuthInterceptor extends HandlerInterceptorAdapter {
	
	/** 日志类 */
	public Logger log = Logger.getLogger(this.getClass());
	/** 排除的请求路径 */
	private String[] outUrls = new String[]{
												"/login",	//登录
											};
	/** admin url前缀 */
	private String adminUrlPrefix = "/admin";
	@Override
	public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
		boolean flag = true;
	/*	String url = req.getRequestURI();
		log.debug("当前请求URL："+url);
		
		if(!isOutUrl(url) && -1<url.indexOf(adminUrlPrefix)){
			if(SessionContext.isUserLogin(req)){
//				if(SessionContext.isUserStop(req)){
//					log.debug("用户已停用！");
//					noPower("对不起，您的账号已停用！", res);
//					flag = false;
//				} else {
					log.debug("用户已登录！");
				//}
			} else {
				log.debug("用户未登录！");
				timeoutMsg("对话超时，请先登录！", res);
				flag = false;
			}
		} else {
			log.debug("属于排除的URL："+url);
		}*/
		return true;
	}
	/**
	 * 登录超时
	 * @param msg
	 * @return
	 * @throws IOException 
	 */
	public void timeoutMsg(String msg, HttpServletResponse res) throws IOException{
		log.debug(msg);
		writeHTML(JsonUtil.toJson(new DwzStatusBean(301,msg,"","","","")),res);
	}
	/**
	 * 没有权限
	 * @param msg
	 * @return
	 * @throws IOException 
	 */
	public void noPower(String msg, HttpServletResponse res) throws IOException{
		log.debug(msg);
		writeHTML(JsonUtil.toJson(new DwzStatusBean(300,msg,"","","","")),res);
	}
	/**
	 * 是否属于排除的URL
	 * @param url 当前请求的URL
	 * @return boolean 返回true表示需要排除的URL；返回false表示不是需要排除的URL
	 */
	public boolean isOutUrl(String url){
		if(null!=outUrls && 0<outUrls.length){
			for(String s:outUrls){
				if(url.equals(s.trim())){
					return true;
				}
			}
		}
		return false;
	}
	/**
	 * 输出HTML代码
	 * @param html html代码
	 * @param response
	 * @throws IOException 
	 */
	public void writeHTML(String html, HttpServletResponse response) throws IOException{
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter writer = null;;
		try {
			writer = response.getWriter();
			writer.write(html);
			writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if(null!=writer){
				writer.close();
			}
		}
	}
}
